﻿using Common.Core.Data;
using Common.Core.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Common.EventBus.CapRabbitMQ
{
    public static class CapRabbitMQExtensions
    {
        /// <summary>
        /// 自动注册cap rabbitmq版本
        /// </summary>
        /// <param name="services"></param>
        public static void AddCapRabbitMQ(this IServiceCollection services, IConfiguration Configuration)
        {
            // 是否启用RabbitMQ 
            bool IsUseRabbitMQ = Configuration.GetSection("RabbitMQProvider:UseRabbitMQ").Value.ToBool(false);
            if (IsUseRabbitMQ)
            {
                var connection = DBServerProvider.GetDBConnection(services);

                string hostName = Configuration.GetSection("RabbitMQProvider:HostName").Value;
                int port = Configuration.GetSection("RabbitMQProvider:Port").Value.ToInt(5672);
                string userName = Configuration.GetSection("RabbitMQProvider:UserName").Value;
                string password = Configuration.GetSection("RabbitMQProvider:Password").Value;
                string virtualHost = Configuration.GetSection("RabbitMQProvider:VirtualHost").Value;
                string exchangeName = Configuration.GetSection("RabbitMQProvider:ExchangeName").Value;
                if (string.IsNullOrWhiteSpace(exchangeName))
                {
                    exchangeName = "cbmnet.router";
                }

                services.AddCap(x =>
                {
                    //如果你使用的ADO.NET，根据数据库选择进行配置：
                    x.UseMySql(connection.MassterDB.ConnectionString);

                    //CAP支持 RabbitMQ、Kafka、AzureServiceBus、AmazonSQS 等作为MQ，根据使用选择配置：
                    x.UseRabbitMQ(o =>
                    {
                        o.HostName = hostName;
                        o.Port = port;
                        o.UserName = userName;
                        o.Password = password;
                        o.VirtualHost = virtualHost;
                        o.ExchangeName = exchangeName;
                    });
                });
            }
        }
    }
}
